#include "graphics.h" 
#include "stdio.h" 
#include "stdlib.h" 

#define POS0 110 
#define POS1 320 
#define POS2 530 
#define MAXN 20 
#define BLINE 390 
#define WIDTH (textwidth("H")*1) 
#define HEIGHT (textheight("H")*2) 
#define IMAGE_SIZE 10 

int needls[3]; 
int pos[3]={POS0,POS1,POS2}; 
char *pieces[3][MAXN]; 

void init(int n) 
{ 
int GraphDriver=DETECT,GraphMode; 
int i,j,size,left,top,right,bottom; 
needls[0]=n; 
needls[1]=0; 
needls[2]=0; 
registerbgidriver(EGAVGA_driver); 
initgraph(&GraphDriver,&GraphMode,""); 
bar(5,BLINE,getmaxx()-5,BLINE+HEIGHT); 
for(i=n-1;i>=0;i--) 
{ j=n-i-1; 
left=pos[0]-WIDTH*(i+1)/2; 
top=BLINE-HEIGHT*(j+1)-j-1; 
right=2*pos[0]-left; 
bottom=top+HEIGHT; 
setfillstyle(i%12,i%getmaxcolor()); 
bar(left+1,top+1,right-1,bottom-1); 
rectangle(left,top,right,bottom); 
size=imagesize(left,top,right,bottom); 
pieces[0][j]=(char *)malloc(size); 
getimage(left,top,right,bottom,pieces[0][j]); 
pieces[1][j]=pieces[2][j]=NULL; 
} 
} 

void move(top1,left1,top2,left2,pieces) 
int top1,left1,top2,left2; 
char *pieces; 
{ 
int top,left; 
int loop,i,k; 
long j,t; 
loop=(abs(top1-top2)>abs(left1-left2))?abs(top1-top2):abs(left1-left2); 
for(i=0;i<loop;i++) 
for(k=0;k<2;k++) 
{ t=(long)(k+i); 
t *= (long)(left2-left1); 
t /=loop; 
left=left1+(int)t; 
t=(long)(k+i); 
t *=(long)(top2-top1); 
t /=loop; 
top=top1+(int)t; 
putimage(left,top,pieces,XOR_PUT); 
for(j=0;j<1000*k;j++); 
} 
t=(long)loop; 
t *=(long)(left2-left1); 
t /=loop; 
left=left1+(int)t; 
t=(long)loop; 
t *=(long)(top2-top1); 
t /=loop; 
top=top1+(int)t; 
putimage(left,top,pieces,XOR_PUT); 
putimage(left2,top2,pieces,XOR_PUT); 
} 

void hanoi(int h,int f,int u,int t) 
{ int k,left1,top1,left2,top2; 
if(h>0) 
{ hanoi(h-1,f,t,u); 
k=needls[f]--; 
left1=pos[f]-WIDTH*h/2; 
top1=BLINE-HEIGHT*k-needls[f]-1; 
pieces[t][needls[t]++]=pieces[f][k-1]; 
pieces[f][k-1]=NULL; 
left2=pos[t]-WIDTH*h/2; 
top2=BLINE-HEIGHT*needls[t]-needls[t]; 
move(top1,left1,top2,left2,pieces[t][needls[t]-1]); 
delay(1000L); 
hanoi(h-1,u,f,t); 
} 
} 

void freeimage(int n) 
{ int i,j; 
for(i=0;i<3;i++) 
for(j=0;j<n;j++) 
if(pieces[i][j]) 
free(pieces[i][j]); 
} 

void main() 
{ int n,x,y; 
while(1) 
{ 
n=20; 
init(n); 
x=wherex();y=wherey(); 
gotoxy(50,20); 
setcolor(14+128); 
settextstyle(1,0,1); 
outtextxy(250,30,"Made by Zou Hongwei"); 
gotoxy(x,y); 
settextstyle(0,0,0); 
hanoi(n,0,2,1); 
getchar(); 
delay(1000l); 
freeimage(n); 
closegraph(); 
} 
}